package cn.hsp.tiktok

import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import cn.hsp.tiktok.network.NetworkService
import cn.hsp.tiktok.view.*
import kotlinx.android.synthetic.main.fragment_video_list.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class HomeVideoListFragment : Fragment() {
    private var urlList = mutableListOf<String>()

    /** 当前播放视频位置  */
    private var curPlayPosition = -1
    private var viewPagerLayoutManager: ViewPagerLayoutManager? = null
    private var videoView: FullScreenVideoView? = null
    private var ivCurCover: ImageView? = null
    private var adapter: VideoAdapter? = null
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_video_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    private fun init() {
        adapter = VideoAdapter(activity)
        recyclerView!!.adapter = adapter
        videoView = FullScreenVideoView(activity as FragmentActivity)
        setViewPagerLayoutManager()
        setRefreshLayout()

        //监听播放或暂停事件
//        val subscribe = RxBus.getDefault().toObservable(PauseVideoEvent::class.java)
//            .subscribe(Action1 { event: PauseVideoEvent ->
//                if (event.isPlayOrPause) {
//                    videoView.start()
//                } else {
//                    videoView.pause()
//                }
//            } as Action1<PauseVideoEvent>)
//        subscribe.unsubscribe()
        queryData()
    }

    private fun setRefreshLayout() {
        refreshLayout.setColorSchemeResources(R.color.color_link)
        refreshLayout.setOnRefreshListener {
            object : CountDownTimer(1000, 1000) {
                override fun onTick(millisUntilFinished: Long) {}
                override fun onFinish() {
                    refreshLayout.isRefreshing = false
                }
            }.start()
        }
    }

    private fun setViewPagerLayoutManager() {
        viewPagerLayoutManager = ViewPagerLayoutManager(activity as FragmentActivity)
        recyclerView!!.layoutManager = viewPagerLayoutManager
        viewPagerLayoutManager!!.setOnViewPagerListener(object : OnViewPagerListener {
            override fun onInitComplete() {
                playVideo(0)
            }

            override fun onPageRelease(isNext: Boolean, position: Int) {
                if (ivCurCover != null) {
                    ivCurCover!!.visibility = View.VISIBLE
                }
            }

            override fun onPageSelected(position: Int, isBottom: Boolean) {
                playVideo(position)
            }
        })
    }

    private fun playVideo(position: Int) {
        if (position == curPlayPosition) {
            return
        }
        val itemView = viewPagerLayoutManager!!.findViewByPosition(position) ?: return
        val rootView = itemView.findViewById<ViewGroup>(R.id.rl_container)
        val likeView: LikeView = rootView.findViewById(R.id.likeView)
        val controllerView: ControllerView = rootView.findViewById(R.id.controllerView)
        val ivPlay = rootView.findViewById<ImageView>(R.id.playIv)
        val ivCover = rootView.findViewById<ImageView>(R.id.coverIv)
        ivPlay.alpha = 0.4f

        //播放暂停事件
        likeView.setOnPlayPauseListener(object : LikeView.OnPlayPauseListener {
            override fun onPlayOrPause() {
                if (videoView?.isPlaying == true) {
                    videoView?.pause()
                    ivPlay.visibility = View.VISIBLE
                } else {
                    videoView?.start()
                    ivPlay.visibility = View.GONE
                }
            }

        })

        //评论点赞事件
//        likeShareEvent(controllerView)

        curPlayPosition = position

        //切换播放器位置
        changeVideoViewToCurrentPage(rootView)
        autoPlayVideo(curPlayPosition, ivCover)
    }

    private fun changeVideoViewToCurrentPage(rootView: ViewGroup) {
        //1.添加videoview到当前需要播放的item中,添加进item之前，保证ijkVideoView没有父view
        videoView?.parent?.let { (it as ViewGroup).removeView(videoView) }
        rootView.addView(videoView, 0)
    }

    /**
     * 自动播放视频
     */
    private fun autoPlayVideo(position: Int, ivCover: ImageView) {
        val videoFilePath = adapter?.getData(position)?.videoUrl
        videoView?.setVideoURI(Uri.parse(videoFilePath))
        videoView?.start()
        videoView?.setOnPreparedListener { mp: MediaPlayer ->
            mp.isLooping = true

            //延迟取消封面，避免加载视频黑屏
            object : CountDownTimer(200, 200) {
                override fun onTick(millisUntilFinished: Long) {}
                override fun onFinish() {
                    ivCover.visibility = View.GONE
                    ivCurCover = ivCover
                }
            }.start()
        }
    }

    private fun queryData() {
        val networkService = getNetworkService()
        MainScope().launch(Dispatchers.Main) {
            val resp = withContext(Dispatchers.IO) { networkService.query() }
            val videoBeans = ArrayList<VideoBean>()

            resp.videos.forEach {
                val videoBean = VideoBean()
                videoBean.videoUrl = it.videoUrl
                videoBean.coverUrl = it.coverUrl
                videoBean.content = it.content
                videoBeans.add(videoBean)
            }
            activity?.let {
                adapter?.setData(videoBeans)
            }
        }
    }

    private fun getNetworkService(): NetworkService {
        val okHttpClient = OkHttpClient.Builder().build()
        val retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl("https://gitee.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        return retrofit.create(NetworkService::class.java)
    }
}